package com.chenyanqing.sqlsession;

import com.chenyanqing.config.BoundSql;
import com.chenyanqing.config.Configuration;
import com.chenyanqing.pojo.MapperStatement;
import com.chenyanqing.utils.GenericTokenParser;
import com.chenyanqing.utils.ParameterMapping;
import com.chenyanqing.utils.ParameterMappingTokenHandler;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


/**
 * 陈妍青
 */
public class SimplerExecutor implements  Executor {
    @Override
    public <T> List<T> query(Configuration configuration, MapperStatement mapperStatement, Object... objects) throws Exception {

        //1\    注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //2、获取sql语句  包含# {},jdbc不能识别，转换为？占位符的sql
        String sql= mapperStatement.getSql();
        BoundSql  boundSql = getBoundSql(sql);


        //3、获取预处理对象 prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());


        //4、设置参数
        //获取参数的全路径，string
        String paramType = mapperStatement.getParamType();
        Class<?> classType = getClassType(paramType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String property = parameterMapping.getContent();

            //反射
            Field declaredField = classType.getDeclaredField(property);
            //暴力访问
            declaredField.setAccessible(true);

            Object o  = declaredField.get(objects[0]);
            preparedStatement.setObject(i+1,o);
        }
        


        //5、执行sql
        ResultSet resultSet = preparedStatement.executeQuery();


        //6、返回结果集,对resultSet进行遍历
        String resultType = mapperStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> rObjects = new ArrayList<>();

        while (resultSet.next()){
            Object o =resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);


            }
            rObjects.add(o);

        }
       return (List<T>) rObjects;

    }

    @Override
    public int update(Configuration configuration, MapperStatement mappedStatement, Object... params) throws Exception {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4. 设置参数
        //获取到了参数的全路径
        String paramterType = mappedStatement.getParamType();
        Class<?> paramtertypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = paramtertypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }


        // 5. 执行sql
        int i = preparedStatement.executeUpdate();
        return i;
    }




    //根据某个全路径 获取一个class
    private Class<?> getClassType(String paramType) throws ClassNotFoundException {
        if(StringUtils.isNotBlank(paramType)){
            return Class.forName(paramType);
        }
       return null;
    }


    /**
     * 完成对# {}  进行解析
     * 1、将#{}用问号代替
     * 2、解析出#{}里面的值进行存储
     * @return
     */
    private BoundSql getBoundSql(String sql){
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}",tokenHandler);

        //解析出来❓占位的sql
        String parse = genericTokenParser.parse(sql);

        //解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        return new BoundSql(parse,parameterMappings);
    }





}
